package com.edais.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.edais.domain.ErrorMessageSetting;
import com.edais.mina.TcpMinaClient;
import com.edais.service.ErrorMessageService;

import net.sf.json.JSONObject;

/**
 * 常用公共方法
 */
@Service("commonUtil")
public class CommonUtil {

	private static final Logger logger = Logger.getLogger(CommonUtil.class);

	@Autowired
	private ErrorMessageService errorMessageService;

	private static CommonUtil commonUtil;

	public void setErrorMessageService(ErrorMessageService errorMessageService) {
		this.errorMessageService = errorMessageService;
	}

	@PostConstruct
	public void init() {
		commonUtil = this;
		commonUtil.errorMessageService = this.errorMessageService;
	}

	/**
	 * 设置分页参数
	 * 
	 * @param parameters
	 * @return Map<String, Object>
	 */
	public static Map<String, Object> setPaging(Map<String, Object> parameters) {

		String currentStr = String.valueOf(parameters.get(CommonConstant.CURRENT));
		if (StringUtil.isEmpty(currentStr))
			currentStr = "1";

		String pageSizeStr = String.valueOf(parameters.get(CommonConstant.PAGE_SIZE));
		if (StringUtil.isEmpty(pageSizeStr))
			pageSizeStr = "10";

		int current = Integer.parseInt(currentStr);
		int pageSize = Integer.parseInt(pageSizeStr);

		logger.info("---------------------------------------------------------CommonUtil setPaging() current=" + current
				+ " , pageSize=" + pageSize + "---------------------------------------------------------");

		parameters.put("rowBegin", (current - 1) * pageSize + 1);
		parameters.put("rowEnd", current * pageSize);

		return parameters;
	}

	/**
	 * 将异常堆栈的信息转成String
	 * 
	 * @param throwable
	 * @return String
	 */
	public static String printStackTraceToString(Throwable throwable) {

		StringWriter stringWriter = new StringWriter();

		throwable.printStackTrace(new PrintWriter(stringWriter, true));

		String result = stringWriter.getBuffer().toString();

		try {

			stringWriter.close();

		} catch (IOException e) {

			logger.info("---------------------------------------CommonUtil printStackTraceToString() 关闭输出流出现异常!"
					+ e.getMessage() + "----------------------------------------------------");

			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 将json格式的字符串解析成Map对象
	 * <li>json格式：{"name":"admin","retries":"3fff","testname"
	 * :"ddd","testretries":"fffffffff"}
	 */
	public static HashMap<String, Object> jsonObjToHashMap(Object object) {
		HashMap<String, Object> data = new HashMap<String, Object>();
		// 将json字符串转换成jsonObject
		JSONObject jsonObject = JSONObject.fromObject(object);
		Iterator it = jsonObject.keys();
		// 遍历jsonObject数据，添加到Map对象
		while (it.hasNext()) {
			String key = String.valueOf(it.next());
			Object value = jsonObject.get(key);
			data.put(key, value);
		}
		return data;
	}

	/**
	 * 本方法是将页面传递过来的参数quest.getParameter("")封装在MAP中，最好为LinkedHashMap的进行封装
	 * hashmap是没有排序的，而LinkedHashMap是按着放入参数的顺序组合出来的字符串
	 * 
	 * @param map
	 * @return 返回组合好的参数拼串
	 */
	public static String getParam(Map<String, Object> map) {

		StringBuffer sb = new StringBuffer();
		String param = "";

		try {
			for (String key : map.keySet()) {

				sb.append(key);
				sb.append("=");
				sb.append(map.get(key));
				sb.append("&");

			}
			if (!"".equals(sb.toString().trim()) && sb.toString().trim() != null) {
				param = sb.toString().substring(0, sb.length() - 1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return param;

	}

	/**
	 * @return (00000000+str)返回包括报文长度的字符串
	 * @param str
	 *            action中返回的字符串
	 * @param len
	 *            表示JSON前面的8位的"报文长度"
	 */
	public static String countRtnByte(String str, int len) {
		logger.debug(">>>>>>>>不包含00000000:" + str);
		byte[] byteStr = null;
		try {
			byteStr = str.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			logger.debug("字符串不是UTF-8编码格式");
		}

		int length = byteStr.length;// 报文体长度
		int lengthTotal = length + len;// 报文总长度

		String add0Str = addStr(lengthTotal + "", len);
		return add0Str + str;
	}

	/**
	 * 处理报文,返回包含文长度的字符串
	 * 
	 * @param message:报文
	 * @param splitLength:截取长度(JSON前面的8位的"报文长度")
	 * @return String (00000000+str)返回包括报文长度的字符串
	 */
	public static String handleReturnMessage(String message, int splitLength) {

		logger.info("-------------------------------------------CommonUtil handleReturnMessage() 不包含00000000:" + message
				+ "----------------------------------------------------");

		byte[] bytes = null;

		try {
			bytes = message.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {

			logger.info(
					"-------------------------------------------CommonUtil handleReturnMessage() 返回报文字符串不是UTF-8编码格式!"
							+ CommonUtil.printStackTraceToString(e)
							+ "----------------------------------------------------");

			e.printStackTrace();
		}

		int length = bytes.length;// 报文体长度
		length += splitLength;// 报文总长度

		StringBuffer buffer = leftComplementingBits(length + "", splitLength);

		buffer.append(message);

		return buffer.toString();
	}

	/**
	 * 读取Properties属性文件:
	 * fileName是以src为根目录的文件名称,例:src/config/deal/dealConfig.properties
	 */
	public static Properties parseProperties(Class<?> inputClass, String fileName) {
		logger.debug("文件名称是:" + fileName);
		Properties props = new Properties();

		// method one
		// String path =
		// inputClass.getClass().getResource("/").getPath().substring(1);
		// String filePath = path.substring(0, (path.length() - 4)) + fileName;

		// method two
		String filePath = System.getProperty("user.dir").toString() + fileName;

		logger.debug("文件路径是:" + filePath);
		InputStream fileInputStream = null;// 文件输入流
		try {
			fileInputStream = new FileInputStream(filePath);
			props.load(fileInputStream);
		} catch (FileNotFoundException e) {
			logger.error("/CommonUtil/parseProperties 异常:" + e.getMessage());
		} catch (IOException e) {
			logger.error("/CommonUtil/parseProperties 异常:" + e.getMessage());
		} finally {
			try {
				if (fileInputStream != null) {
					fileInputStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return props;
	}

	/**
	 * 补齐len位,不足左补0
	 */
	public static String addStr(String str, int len) {
		String strRtn = "";
		for (int i = 0; i < (len - str.length()); i++) {
			strRtn += "0";
		}
		strRtn = strRtn + str;
		return strRtn;
	}

	/**
	 * 补齐bitsLength位,不足左补0
	 * 
	 * @param source:源字符串
	 * @param bitsLength:补齐位数
	 */
	public static StringBuffer leftComplementingBits(String source, int bitsLength) {

		StringBuffer buffer = new StringBuffer();

		int length = source.length();
		length = bitsLength - length;

		for (int i = 0; i < length; i++) {

			buffer.append("0");

		}

		buffer.append(source);

		return buffer;
	}

	/**
	 * 构建json字符串
	 * 
	 * @param transCode
	 *            交易码
	 * @param sysuserid
	 *            操作人ID
	 * @param pageModel
	 *            报文体Model
	 * @return
	 */
	public static String constructJsonStr(String transCode, String sysuserid, Map<String, Object> pageModel)
			throws Exception {
		// 系统时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
		String sysdate = sdf.format(new Date());

		pageModel.put("iface", transCode);
		pageModel.put("sysuserid", sysuserid);
		pageModel.put("sysdate", sysdate);

		return JsonUtil.getJsonStringFromMap(pageModel);
	}

	/**
	 * 调用核心接口
	 * 
	 * @param jsonStr
	 * @return
	 */
	public static String getCoreValue(String jsonStr) throws Exception {
		TcpMinaClient tcpMinaClient = new TcpMinaClient();
		String rtnStr = tcpMinaClient.sendMessage(jsonStr);
		logger.debug(">>>>>>>responsemessage:" + rtnStr);

		rtnStr = rtnStr.substring(8, rtnStr.length());

		return rtnStr;
	}

	/**
	 * 调用核心接口
	 */
	public static Map coreUse(String userId, String transCode, Map<String, Object> pageModel) throws Exception {
		String jsonStr = CommonUtil.constructJsonStr(transCode, userId, pageModel);// 构建json字符串
		Map rtnMap = (HashMap) JsonUtil.getObjectFromJsonString(getCoreValue(jsonStr), HashMap.class);
		return rtnMap;
	}

	/**
	 * 调用核心
	 */
	@SuppressWarnings("rawtypes")
	public static Map invokeCore(String logInfo, String serviceName, Map<String, Object> map) {
		map.put("iface", "C000000");
		if (map.containsKey("userId")) {
			map.put("sysuserid", map.get("userId"));
		} else {
			map.put("sysuserid", "-1");
		}
		map.put("sysdate", new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()));
		map.put("logInfo", logInfo);
		map.put("serviceName", serviceName);
		String reqJsonString = JsonUtil.getJsonStringFromMap(map);
		logger.info(logInfo + "调用核心：" + reqJsonString);
		TcpMinaClient tcpMinaClient = new TcpMinaClient();
		String resJsonString = tcpMinaClient.sendMessage(reqJsonString);
		logger.info(logInfo + "核心返回：" + resJsonString);
		resJsonString = resJsonString.substring(8);
		Map rtnMap = (HashMap) JsonUtil.getObjectFromJsonString(resJsonString, HashMap.class);
		return rtnMap;
	}

	// /**
	// * 把传入的对象转成json
	// * */
	// public static String createJson(Object obj) throws Exception {
	// ObjectMapper objectMapper = new ObjectMapper();
	// return objectMapper.writeValueAsString(obj);
	// }

	/**
	 * 解析请求参数
	 **/
	public static Map<String, String> decryptParamters(HttpServletRequest request) {
		Map<String, String> rtnMap = new HashMap<String, String>();

		try {
			// 获取get参数
			String reqString = request.getQueryString();
			// logger.debug(">>>>>>>>>>>>>>>>获取的参数字符串：" + reqString);

			// if (reqString == null) {
			// //获取post参数
			// InputStream is = request.getInputStream();
			// InputStreamReader isr = new InputStreamReader(is);
			// BufferedReader br = new BufferedReader(isr);
			// // 解码POST提交的参数
			// reqString = java.net.URLDecoder.decode(br.readLine(),"UTF-8");
			// }

			if (StringUtils.isNotBlank(reqString)) {
				// 解密 Base64 + 3DES
//				String paramters = DES3Util.decode(reqString);
				 String paramters = reqString;
				// // 特殊字符、中文汉字转码
				paramters = java.net.URLDecoder.decode(paramters, "UTF-8");

//				 String paramters = reqString;

				// logger.debug("请求参数列表：");
				String[] tmpArr = paramters.split("&");
				for (int i = 0; i < tmpArr.length; i++) {
					// logger.debug("*************" + tmpArr[i]);

					String[] paramArr = tmpArr[i].split("=");
					if (paramArr.length == 1) { // 参数值为空
						rtnMap.put(paramArr[0], "");
					} else if (paramArr.length == 2) {
						rtnMap.put(paramArr[0], paramArr[1]);
					} else {

					}
				}
			}
		} catch (Exception e) {
			logger.debug("请求参数解析异常：" + e.getMessage());
		}

		return rtnMap;
	}

	/**
	 * 解析请求参数
	 **/
	public static Map<String, String> decryptParamtersShop(HttpServletRequest request) {
		Map<String, String> rtnMap = new HashMap<String, String>();

		try {
			// 获取get参数
			String reqString = request.getQueryString();
			// logger.debug(">>>>>>>>>>>>>>>>获取的参数字符串：" + reqString);

			// if (reqString == null) {
			// //获取post参数
			// InputStream is = request.getInputStream();
			// InputStreamReader isr = new InputStreamReader(is);
			// BufferedReader br = new BufferedReader(isr);
			// // 解码POST提交的参数
			// reqString = java.net.URLDecoder.decode(br.readLine(),"UTF-8");
			// }

			if (StringUtils.isNotBlank(reqString)) {
				// 解密 Base64 + 3DES
				String paramters = DES3Util.decodeShop(reqString);
				// String paramters = reqString;
				// // 特殊字符、中文汉字转码
				paramters = java.net.URLDecoder.decode(paramters, "UTF-8");

				// String paramters = reqString;

				// logger.debug("请求参数列表：");
				String[] tmpArr = paramters.split("&");
				for (int i = 0; i < tmpArr.length; i++) {
					// logger.debug("*************" + tmpArr[i]);

					String[] paramArr = tmpArr[i].split("=");
					if (paramArr.length == 1) { // 参数值为空
						rtnMap.put(paramArr[0], "");
					} else if (paramArr.length == 2) {
						rtnMap.put(paramArr[0], paramArr[1]);
					} else {

					}
				}
			}
		} catch (Exception e) {
			logger.debug("请求参数解析异常：" + e.getMessage());
		}

		return rtnMap;
	}

	/**
	 * 解密请求参数
	 * 
	 * @author ZuoJun
	 * @date 2016-7-8 18:06
	 * @param request
	 * @return Map<String, Object>
	 */
	public static Map<String, Object> getDecryptParameter(HttpServletRequest request) {

		Map<String, Object> returnResult = new HashMap<String, Object>();

		try {
			// 获取GET请求参数
			String queryString = request.getQueryString();

			logger.info(
					"----------------------------------------CommonUtil getDecryptParameter() 解密前请求参数  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< requestString="
							+ queryString
							+ " <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<--------------------------------------------------------");

			if (StringUtil.isNotEmpty(queryString)) {
				// 解密 Base64 + 3DES
				String paramters = DES3Util.decode(queryString);

				// 特殊字符、中文汉字转码
				paramters = URLDecoder.decode(paramters, "UTF-8");

				logger.info(
						"----------------------------------------CommonUtil getDecryptParameter() 解密后请求参数 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> paramters="
								+ paramters
								+ " >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>--------------------------------------------------------");

				String[] tmpArr = paramters.split("&");

				int len = tmpArr.length;

				for (int i = 0; i < len; i++) {

					String[] paramArr = tmpArr[i].split("=");

					int length = paramArr.length;

					if (length == 1) {// 参数值为空

						returnResult.put(paramArr[0], "");

					} else if (length == 2) {

						returnResult.put(paramArr[0], paramArr[1]);

					}
				}
			}
		} catch (Exception e) {

			logger.info("----------------------------------------CommonUtil getDecryptParameter() 解密请求参数出现异常 "
					+ printStackTraceToString(e) + "--------------------------------------------------------");
			e.printStackTrace();

		}

		return returnResult;
	}

	/**
	 * json返回客户端(加密)
	 * 
	 * @throws UnsupportedEncodingException
	 **/
	public static void responseJson(Object result, HttpServletResponse response) {
		String encodeStr = "";
		try {
			logger.debug(">>>>>>>>>>>>>>>>>>>>>>返回结果加密前：" + result);
			// 特殊字符、中文汉字转码
			encodeStr = java.net.URLEncoder.encode(String.valueOf(result), "utf-8");
			// 加密返回json串
			encodeStr = DES3Util.encode(encodeStr);

			// logger.debug(">>>>>>>>>>>>>>>>>>>>>>返回结果加密后：" + encodeStr);
		} catch (Exception e) {
			logger.debug("返回结果加密异常：" + e.getMessage());
		}

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter out = response.getWriter();
//			 out.print(result);
			out.print(encodeStr);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("/CommonUtil/responseJson 异常:" + e.getMessage());
		}
	}

	/**
	 * json返回客户端(加密)(电商)
	 * 
	 * @throws UnsupportedEncodingException
	 **/
	public static void responseJsonShop(Object result, HttpServletResponse response) {
		String encodeStr = "";
		try {
			logger.debug(">>>>>>>>>>>>>>>>>>>>>>返回结果加密前：" + result);
			// 特殊字符、中文汉字转码
			encodeStr = java.net.URLEncoder.encode(String.valueOf(result), "utf-8");
			// 加密返回json串
			encodeStr = DES3Util.encodeShop(encodeStr);

			// logger.debug(">>>>>>>>>>>>>>>>>>>>>>返回结果加密后：" + encodeStr);
		} catch (Exception e) {
			logger.debug("返回结果加密异常：" + e.getMessage());
		}

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter out = response.getWriter();
			// out.print(result);
			out.print(encodeStr);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("/CommonUtil/responseJson 异常:" + e.getMessage());
		}
	}

	public static void responseErrorJsonByErrNo(String errType, String errNo, HttpServletResponse response)
			throws Exception {
		Map<String, Object> errorMap = commonUtil.errorMessageService.getErrorMessage(errNo);
		String errMsg = getErrorMsg(errorMap);
		StringBuffer logMsg = new StringBuffer();
		logMsg.append(errType).append(":").append(errMsg);
		logger.error(logMsg);
		String result = CommonUtil.setResultStringCn(new HashMap<String, Object>(), Consts.CHECK_CODE, "", errMsg);// 处理返回结果
		CommonUtil.responseJson(result, response);
	}

	/**
	 * json返回客户端(不加密)
	 * 
	 * @throws UnsupportedEncodingException
	 **/
	public static void responseJsonNotEncrypt(Object result, HttpServletResponse response) {

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter out = response.getWriter();
			out.print(result);
			out.flush();
			out.close();
		} catch (IOException e) {
			logger.error("/CommonUtil/responseJsonNotEncrypt 异常:" + e.getMessage());
		}
	}

	/**
	 * 获取随机验证码:随机产生的6位数字
	 */
	public static String getRandomCode() {
		// 获取验证码
		String randomCode = "";
		// 验证码字符个数
		int codeCount = 6;
		// 创建一个随机数生成器类
		Random random = new Random();
		// 随机产生codeCount数字的验证码
		for (int i = 0; i < codeCount; i++) {
			// 得到随机产生的验证码数字
			String strRand = String.valueOf(random.nextInt(10));
			randomCode += strRand;
		}
		return randomCode;
	}

	/**
	 * 获取随机验证码:随机产生的4位数字
	 */
	public static String getRandomCode_Four() {
		// 获取验证码
		String randomCode = "";
		// 验证码字符个数
		int codeCount = 4;
		// 创建一个随机数生成器类
		Random random = new Random();
		// 随机产生codeCount数字的验证码
		for (int i = 0; i < codeCount; i++) {
			// 得到随机产生的验证码数字
			String strRand = String.valueOf(random.nextInt(10));
			randomCode += strRand;
		}
		return randomCode;
	}

	/**
	 * 生成订单号
	 * 
	 * 订单号格式:20140510(日期) + 1399540001193(当时系统的毫秒数)
	 * 
	 */
	public static String createTime() {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String formatStr = sdf.format(date);// 20140508
		String dateStr = date.getTime() + "";// 1399540001193
		String now = formatStr + dateStr;

		return now;
	}

	/**
	 * 设置返回rescode、resmsg
	 * 
	 */
	public static String setResultInfo(Map<String, Object> map, String rescode, String resmsg) {
		map.put("rescode", rescode);
		map.put("resmsg", resmsg);
		// 处理返回结果
		return JsonUtil.getJsonStringFromMap(map);
	}

	/**
	 * 设置返回rescode、resmsg、resmsg_cn
	 * 
	 */
	public static String setResultStringCn(Map<String, Object> map, String rescode, String resmsg, String resmsgCn) {
		map.put("rescode", rescode);
		map.put("resmsg", resmsg);
		map.put("resmsg_cn", resmsgCn);
		// 处理返回结果
		return JsonUtil.getJsonStringFromMap(map);
	}

	/**
	 * 设置返回列表
	 * 
	 * @param returnResult:返回数据
	 * @param result:列表
	 * @param totalNum:总条数
	 * @param rescode
	 * @param resmsg
	 * @param resmsgCn
	 * @return Map<String, Object>
	 */
	public static Map<String, Object> setResult(Map<String, Object> returnResult, List result, int totalNum,
			String rescode, String resmsg, String resmsgCn) {

		returnResult.put(CommonConstant.RES_CODE, rescode);
		returnResult.put(CommonConstant.TOTAL_NUM, totalNum);
		returnResult.put(CommonConstant.LIST_SIZE, result != null ? result.size() : 0);
		returnResult.put(CommonConstant.LIST, result);
		returnResult.put(CommonConstant.RES_MSG, resmsg);
		returnResult.put(CommonConstant.RES_MSG_CN, resmsgCn);

		return returnResult;
	}

	/**
	 * 设置返回数据
	 * 
	 * @param response
	 * @param result
	 * @param args:rescode,resmsg,resmsgCn
	 * 
	 */
	public static void setResponse(HttpServletResponse response, Map<String, Object> result, String... args) {

		int len = args.length;

		String resCode = "";
		String resMsg = "";
		String resMsgCn = "";

		if (len > 2) {

			resCode = args[0];
			resMsg = args[1];
			resMsgCn = args[2];

		} else if (len > 1) {

			resCode = args[0];
			resMsg = args[1];

		} else if (len > 0) {

			resCode = args[0];
		}

		if (StringUtil.isNotEmpty(resCode))
			result.put(CommonConstant.RES_CODE, resCode);

		if (StringUtil.isNotEmpty(resMsg))
			result.put(CommonConstant.RES_MSG, resMsg);

		if (StringUtil.isNotEmpty(resMsgCn))
			result.put(CommonConstant.RES_MSG_CN, resMsgCn);

		String jsonString = JsonUtil.getJsonStringFromMap(result);

		logger.info("----------------------------------------CommonUtil setResponse() 加密前返回数据:" + jsonString
				+ "-------------------------------------------------------------");

		String resonseResult = "";

		try {
			// 特殊字符、中文汉字转码
			resonseResult = URLEncoder.encode(jsonString, "UTF-8");

		} catch (UnsupportedEncodingException e) {

			logger.info("-------------------------------------CommonUtil setResponse() 转码出现异常!"
					+ CommonUtil.printStackTraceToString(e)
					+ "------------------------------------------------------------");
			e.printStackTrace();
		}

		try {
			// 加密返回json字符串
			resonseResult = DES3Util.encode(resonseResult);

			logger.info("----------------------------------------CommonUtil setResponse() 加密后返回数据:" + resonseResult
					+ "-------------------------------------------------------------");
		} catch (Exception e) {

			logger.info("-------------------------------------CommonUtil setResponse() 加密出现异常!"
					+ CommonUtil.printStackTraceToString(e)
					+ "------------------------------------------------------------");
			e.printStackTrace();
		}

		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=utf-8");

		PrintWriter out = null;

		try {

			out = response.getWriter();
			out.print(resonseResult);
			out.flush();

		} catch (IOException e) {

			logger.info("-----------------------------------------CommonUtil setResponse() 响应出现异常!"
					+ CommonUtil.printStackTraceToString(e)
					+ "-----------------------------------------------------------");

			e.printStackTrace();

		} finally {

			if (out != null) {
				out.close();
			}

		}

	}

	/**
	 * 金额判断大小
	 * 
	 */
	public static int checkAmount(BigDecimal amount1, BigDecimal amount2) {
		// -1表示小于，0是等于，1是大于
		return amount1.compareTo(amount2);
	}

	/**
	 * 年龄判断
	 * 
	 */
	public static int checkAge(int compareObj1, int compareObj2) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.YEAR, -compareObj2);
		SimpleDateFormat sf = new SimpleDateFormat("yyyyMMdd");
		String str = sf.format(calendar.getTime());
		if (Integer.parseInt(str) == compareObj1) {
			return 0;// 等于
		} else if (Integer.parseInt(str) > compareObj1) {
			return 1;// 大于
		} else {
			return -1;// 小于
		}
	}

	/**
	 * 获取系统时间
	 * 
	 */
	public static String getNow(String formatStr) {
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sf = new SimpleDateFormat(formatStr);
		String str = sf.format(calendar.getTime());
		return str;
	}

	private static String getOracleSQLIn(List<String> ids, int count, String field) {
		count = Math.min(count, 1000);
		int len = ids.size();
		int size = len % count;
		if (size == 0) {
			size = len / count;
		} else {
			size = (len / count) + 1;
		}
		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < size; i++) {
			int fromIndex = i * count;
			int toIndex = Math.min(fromIndex + count, len);
			String productId = StringUtils.defaultIfEmpty(StringUtils.join(ids.subList(fromIndex, toIndex), "','"), "");
			if (i != 0) {
				builder.append(" or ");
			}
			builder.append(field).append(" in ('").append(productId).append("')");
		}

		return StringUtils.defaultIfEmpty(builder.toString(), field + " in ('')");
	}

	/**
	 * 获取uuid
	 * 
	 */
	public static String getUuid() {
		UUID uuid = UUID.randomUUID();
		String str = uuid.toString();
		// 去掉"-"符号
		String temp = str.substring(0, 8) + str.substring(9, 13) + str.substring(14, 18) + str.substring(19, 23)
				+ str.substring(24);
		return temp;
	}

	/**
	 * 获取客户端真实IP
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			int index = ip.indexOf(",");
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		}
		ip = request.getHeader("X-Real-IP");
		if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
			return ip;
		}
		return request.getRemoteAddr();
	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("发送GET请求出现异常！" + e);
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * 
	 * @param url
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPostByHttp(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("contentType", "UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("发送Http的POST 请求出现异常！", e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error("关闭流异常", ex);
			}
		}
		return result;
	}

	/**
	 * Map的数据转换成POST请求参数的格式。 name1=value1&name2=value2 的形式。
	 */
	public static String getHttpParameterFromMap(Map<String, String> map) {
		StringBuffer stringBuffer = new StringBuffer();

		for (Map.Entry<String, String> entry : map.entrySet()) {
			try {
				stringBuffer.append(entry.getKey()).append("=").append(entry.getValue()).append("&");

			} catch (Exception e) {
				logger.error("转换POST请求参数格式出现异常！" + e);
			}
		}
		stringBuffer.deleteCharAt(stringBuffer.length() - 1);

		logger.debug("转换后的POST请求参数串：" + stringBuffer.toString());
		return stringBuffer.toString();
	}

	public static int daysBetween(String smdate, String bdate) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Calendar cal = Calendar.getInstance();
		cal.setTime(sdf.parse(smdate));
		long time1 = cal.getTimeInMillis();
		cal.setTime(sdf.parse(bdate));
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public static int daysBetween(Date smdate, Date bdate) throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public static String getDateYYYYMMDDHH24MM() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		Date d = new Date();
		String dd = format.format(d);
		return dd;
	}

	/**
	 * 
	 * @Description: 指定数字长度，长度不够后面补0
	 * @param str
	 * @param strLength
	 * @return
	 * @return String
	 * @throws @author
	 *             qibo
	 * @date 2015-12-7 下午1:35:06
	 */
	public static String addZeroForNum(String str, int strLength) {
		int strLen = str.length();
		StringBuffer sb = null;
		while (strLen < strLength) {
			sb = new StringBuffer();
			// sb.append("0").append(str);// 左(前)补0
			sb.append(str).append("0");// 右(后)补0
			str = sb.toString();
			strLen = str.length();
		}
		return str;
	}

	/**
	 * ouyy 设置金额格式
	 * 
	 * @param context
	 *            金额
	 * @return
	 */
	public static String setFormatMoney(String context) throws Exception {
		StringBuffer sb = new StringBuffer();
		if (context.lastIndexOf(".") != -1) {
			String pdly = context.substring(context.lastIndexOf(".") + 1);
			if (pdly != null && !"".equals(pdly.trim())) {
				sb.append(context.substring(0, context.lastIndexOf(".") + 1));
				if (pdly != null && pdly.length() == 1) {
					sb.append(pdly + "0");
				} else if (pdly.length() == 2) {
					sb.append(pdly);
				} else if (pdly.length() >= 3) {
					sb.append(pdly.substring(0, 2));
				}
			} else {
				sb.append(context);
			}

		} else {
			sb.append(context + ".00");
		}
		return sb.toString();
	}

	/**
	 * json返回客户端(加密) [非日志打印]
	 * 
	 * @throws UnsupportedEncodingException
	 **/
	public static void responseJsoNoLog(Object result, HttpServletResponse response) {
		String encodeStr = "";
		try {
			// 特殊字符、中文汉字转码
			encodeStr = java.net.URLEncoder.encode(String.valueOf(result), "utf-8");
			// 加密返回json串
			encodeStr = DES3Util.encode(encodeStr);
		} catch (Exception e) {
		}

		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8");
		try {
			PrintWriter out = response.getWriter();
			// out.print(result);
			out.print(encodeStr);
			out.flush();
			out.close();
		} catch (IOException e) {
		}
	}

	/**
	 * 
	 * @Description: 获取错误信息
	 * @param @param
	 *            errorMap
	 * @param @return
	 * @return String
	 * @throws @author
	 *             wuhan
	 * @date 2016-7-13
	 */
	public static String getErrorMsg(Map<String, Object> errorMap) {
		ErrorMessageSetting emsEntity = (ErrorMessageSetting) errorMap.get("errorMessage");
		String emsStr = "";
		if (null != emsEntity) {
			emsStr = emsEntity.getMessage_content();
		}
		return emsStr;
	}

	/**
	 * 执行一个HTTP GET请求，返回请求响应的HTML
	 * 
	 * @param url
	 *            请求的URL地址
	 * @param queryString
	 *            请求的查询参数,可以为null
	 * @return 返回请求响应的HTML
	 * @throws Exception
	 */
	public static String doGet(String url, String queryString) throws Exception {
		String response = null;
		HttpClient client = new HttpClient();
		HttpMethod method = new GetMethod(url);
		try {
			if (StringUtils.isNotBlank(queryString))
				method.setQueryString(URIUtil.encodeQuery(queryString));
			// 链接超时时间设置
			client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
			client.getHttpConnectionManager().getParams().setSoTimeout(120000);
			// 默认尝试三次，当前禁止
			client.getHttpConnectionManager().getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
					new DefaultHttpMethodRetryHandler(0, false));

			client.executeMethod(method);
			if (method.getStatusCode() == HttpStatus.SC_OK) {
				response = method.getResponseBodyAsString();
			}
		} finally {
			method.releaseConnection();
		}

		return response;
	}

	/**
	 * 根据权重抽奖通用方法
	 * 
	 * @param list
	 *            参与抽奖的奖品集合
	 * @param weightFieldName
	 *            奖品对象中的权重字段
	 * @return 抽取到的奖品对象
	 */
	public static <E> E lottery(List<E> list, String weightFieldName) {
		if (list == null || list.isEmpty()) {
			return null;
		}
		// 先移除掉权重为null或0的项，不参与抽奖
		try {
			for (int i = 0; i < list.size(); i++) {
				Field f = list.get(i).getClass().getDeclaredField(weightFieldName);
				f.setAccessible(true);
				String winRate = String.valueOf(f.get(list.get(i)));
				if (winRate == null || "null".equals(winRate) || "0".equals(winRate)) {
					list.remove(i);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		List<BigDecimal> Rates = new ArrayList<BigDecimal>(list.size());
		try {
			for (int i = 0; i < list.size(); i++) {
				Field f = list.get(i).getClass().getDeclaredField(weightFieldName);
				f.setAccessible(true);
				String winRate = String.valueOf(f.get(list.get(i)));
				Rates.add(new BigDecimal(winRate));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (Rates == null || Rates.isEmpty()) {
			return null;
		}
		int size = Rates.size();

		// 计算总概率，这样可以保证不一定总概率是1
		BigDecimal sumRate = new BigDecimal("0.0");
		for (BigDecimal rate : Rates) {
			sumRate = sumRate.add(rate);
		}

		// 计算每个物品在总概率的基础下的概率情况
		List<BigDecimal> sortOrignalRates = new ArrayList<BigDecimal>(size);
		BigDecimal tempSumRate = new BigDecimal("0.0");
		for (BigDecimal rate : Rates) {
			tempSumRate = tempSumRate.add(rate);
			sortOrignalRates.add(tempSumRate.divide(sumRate, 2, BigDecimal.ROUND_FLOOR));
		}

		// 根据区块值来获取抽取到的物品索引
		BigDecimal nextDouble = new BigDecimal(String.valueOf(Math.random()));
		sortOrignalRates.add(nextDouble);
		Collections.sort(sortOrignalRates);

		return list.get(sortOrignalRates.indexOf(nextDouble));
	}

	public static boolean registerPhoneLimitCheck(String phone, String condition) {
		String[] conditions = condition.split("\\|");
		for (int i = 0; i < conditions.length; i++) {
			if (phone.startsWith(conditions[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 相对路径转换为带域名的绝对路径
	 * 
	 * @param domian
	 * @param url
	 * @return
	 */
	public static String getDomianUrl(String domian, String url) {
		if (url == null) {
			return "";
		}
		if (url.startsWith("/")) {
			url = domian + url;
		}
		return url;
	}

	public static Boolean isMoneyAmount(String str) {
		Pattern pattern = Pattern.compile("^(\\d*)(\\.(\\d){0,2})?$");
		Matcher match = pattern.matcher(str);
		if (match.matches() == false) {
			return false;
		} else {
			return true;
		}
	}

	public static void main(String[] args) throws Exception {
		String a = "0.111";
		BigDecimal aBD = new BigDecimal(a);
		System.out.println(aBD.toString());
		System.out.println(CommonUtil.isMoneyAmount(a));
		String b = "0.12";
		BigDecimal bBD = new BigDecimal(b);
		System.out.println(bBD.toString());
		System.out.println(CommonUtil.isMoneyAmount(b));
		String c = ".13";
		BigDecimal cBD = new BigDecimal(c);
		System.out.println(cBD.toString());
		System.out.println(CommonUtil.isMoneyAmount(c));
		String d = "001.14";
		BigDecimal dBD = new BigDecimal(d);
		System.out.println(dBD.toString());
		System.out.println(CommonUtil.isMoneyAmount(d));
		String e = "111.115";
		BigDecimal eBD = new BigDecimal(e);
		System.out.println(eBD.toString());
		System.out.println(CommonUtil.isMoneyAmount(e));
	}
}